package com.lawyer.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.lawyer.config.QiniuConfigBean;
import com.lawyer.entity.RegimentalMember;
import com.lawyer.entity.StationRelStation;
import com.lawyer.entity.User;
import com.lawyer.model.Message;
import com.lawyer.model.MessageConstant;
import com.lawyer.repository.MoneyFlowsRepository;
import com.lawyer.repository.OrderRecommendViewRepository;
import com.lawyer.repository.OrderSuccessQuantityViewRepository;
import com.lawyer.repository.OrderTotalQuantityViewRepository;
import com.lawyer.repository.RegimentalMemberRepository;
import com.lawyer.repository.SettlementAmountViewRepository;
import com.lawyer.repository.StationRelStationRepository;
import com.lawyer.repository.UserRepository;
import com.lawyer.service.FileUpLoadService;
import com.lawyer.service.RegimentalMemberService;

@RestController
@RequestMapping(value = "/system")
@Api(tags = "系统管理-团员管理")
@SuppressWarnings("all")
public class SystemReglMemberController {

	protected final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private UserRepository userRepository;

	@Autowired
	private MoneyFlowsRepository moneyFlowsRepository;

	@Autowired
	private RegimentalMemberRepository regimentalMemberRepository;

	@Autowired
	private EntityManager entityManager;

	@Autowired
	private RegimentalMemberService regimentalMemberService;

	@Autowired
	private SettlementAmountViewRepository settlementAmountViewRepository;

	@Autowired
	private OrderTotalQuantityViewRepository orderTotalQuantityViewRepository;

	@Autowired
	private OrderSuccessQuantityViewRepository orderSuccessQuantityViewRepository;
	@Autowired
	private StationRelStationRepository stationRelStationRepository;
	@Autowired
	private OrderRecommendViewRepository orderRecommendViewRepository;

	@Autowired
	private QiniuConfigBean qiniuConfigBean;

	@Autowired
	private FileUpLoadService fileUpLoadService;

	
	@ApiOperation(httpMethod = "PUT", value = "注册站长,开通站长", notes = "注册站长,开通站长")
	@RequestMapping(value = "/ascensionLeader", method = RequestMethod.PUT)
	public HttpEntity<?> saveOrder(String userId) {
		Message msg = new Message();
		try {
			User leader = userRepository.findOne(userId);
			if (leader == null) {
				msg.setCode(MessageConstant.FAILED_CODE);
				msg.setMessage("没有找到用户");
				return new ResponseEntity<>(msg, HttpStatus.OK);
			}
			RegimentalMember findReg = regimentalMemberRepository.findOne(userId);
			if (findReg != null) {
				msg.setCode(MessageConstant.FAILED_CODE);
				msg.setMessage("已经是站长");
				return new ResponseEntity<>(msg, HttpStatus.OK);
			}
			RegimentalMember regimentalMember = new RegimentalMember();
			regimentalMember.setId(leader.getId());
			regimentalMember.setTopId(leader.getId());
			regimentalMember.setLeaderId(userId);
			regimentalMember.setLeaderHeaderIco(leader.getHeaderIco());
			regimentalMember.setLeaderName(leader.getNickName());
			regimentalMember.setLeaderPhone(leader.getPhone());
			regimentalMember.setStarLevel(2);
			regimentalMemberRepository.save(regimentalMember);
			//开通站长为代理
			leader.setUserType("1");
			userRepository.save(leader);
			
		} catch (Exception e) {
			msg.setCode(MessageConstant.FAILED_CODE);
			msg.setMessage(MessageConstant.FAILED_MSG);
		}

		return new ResponseEntity<>(msg, HttpStatus.OK);
	}

	
	
	
	@ApiOperation(httpMethod = "PUT", value = "站长提升为团长", notes = "StarLevel：1=员团，2=站长，3=团长")
	@RequestMapping(value = "/updateStarLevel", method = RequestMethod.PUT)
	public HttpEntity<?> updateStarLevel(String userId) {
		Message msg = new Message();
		try {
			RegimentalMember regimentalMember = regimentalMemberRepository.findOne(userId);
			if (regimentalMember != null) {
				regimentalMemberRepository.changStarLevel(3, userId);
			} else {
				msg.setCode(MessageConstant.FAILED_CODE);
				msg.setMessage("没有找到该团");
			}
		} catch (Exception e) {
			msg.setCode(MessageConstant.FAILED_CODE);
			msg.setMessage(MessageConstant.FAILED_MSG);
		}

		return new ResponseEntity<>(msg, HttpStatus.OK);
	}
	
	
	@ApiOperation(httpMethod = "PUT", value = "取消站长", notes = "取消站长")
	@RequestMapping(value = "/cancelRegimental", method = RequestMethod.PUT)
	public HttpEntity<?> cancelRegimental(String userId) {
		Message msg = new Message();
		try {
			RegimentalMember regimentalMember = regimentalMemberRepository.findOne(userId);
			if (regimentalMember != null) {
				regimentalMemberRepository.changStarLevel(1, userId);
			} else {
				msg.setCode(MessageConstant.FAILED_CODE);
				msg.setMessage("没有找到该团");
			}
		} catch (Exception e) {
			msg.setCode(MessageConstant.FAILED_CODE);
			msg.setMessage(MessageConstant.FAILED_MSG);
		}

		return new ResponseEntity<>(msg, HttpStatus.OK);
	}
	
	
	
	@ApiOperation(httpMethod = "GET", value = "站长列表查询", notes = "站长列表查询")
	@RequestMapping(value = "/myRegimentalMember", method = RequestMethod.GET)
	@ApiImplicitParams({ @ApiImplicitParam(name = "page", dataType = "integer", paramType = "query", value = "第几页"),
			@ApiImplicitParam(name = "size", dataType = "integer", paramType = "query", value = "分页条数") })
	public HttpEntity<?> myRegimentalMember(@PageableDefault(page = 0, sort = { "createdDate" }, direction = Sort.Direction.DESC) Pageable pageable) {
		Message msg = new Message();

		CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();

		CriteriaQuery<RegimentalMember> criteriaQuery = criteriaBuilder.createQuery(RegimentalMember.class);

		Root<RegimentalMember> root = criteriaQuery.from(RegimentalMember.class);

		criteriaQuery.orderBy(criteriaBuilder.desc(root.get("createdDate")));

		// 查询条件
		List<Predicate> predicates = new ArrayList<>();

		Predicate pred1 = criteriaBuilder.equal(root.get("starLevel"), 2);
		Predicate pred2 = criteriaBuilder.equal(root.get("starLevel"), 3);
		predicates.add(criteriaBuilder.or(pred1, pred2));

		// 将所有条件用 and 联合起来
		if (!CollectionUtils.isEmpty(predicates)) {
			criteriaQuery.where(criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()])));
		}

		List<RegimentalMember> counts = entityManager.createQuery(criteriaQuery).getResultList();
		TypedQuery<RegimentalMember> createQuery = entityManager.createQuery(criteriaQuery);
		createQuery.setFirstResult(pageable.getPageNumber() * pageable.getPageSize());
		createQuery.setMaxResults(pageable.getPageSize());

		Page page = new PageImpl<RegimentalMember>(createQuery.getResultList(), pageable, counts.size());

		msg.setData(page);

		return new ResponseEntity<>(msg, HttpStatus.OK);
	}
	
	
	@ApiOperation(httpMethod = "GET", value = "我的推荐站长列表", notes = "我的推荐站长列表")
	@RequestMapping(value = "/myRecommends", method = RequestMethod.GET)
	@ApiImplicitParams({ @ApiImplicitParam(name = "page", dataType = "integer", paramType = "query", value = "第几页"),
			@ApiImplicitParam(name = "size", dataType = "integer", paramType = "query", value = "分页条数") })
	public HttpEntity<?> myRecommends(String userId, @PageableDefault(page = 0, sort = { "createdDate" }, direction = Sort.Direction.DESC) Pageable pageable) {
		Message msg = new Message();

		if (StringUtils.isEmpty(userId)) {
			msg.setCode(MessageConstant.SUCCESS_CODE);
			return new ResponseEntity<>(msg, HttpStatus.OK);
		}

		Page<StationRelStation> page = stationRelStationRepository.findByMyId(userId, pageable);
		msg.setData(page);

		return new ResponseEntity<>(msg, HttpStatus.OK);
	}
	
}
